package net.ifilm.aspect;

import net.ifilm.common.Constants;
import net.ifilm.common.cache.ICache;
import net.ifilm.entity.*;
import net.ifilm.service.FilmService;
import net.ifilm.service.SiteApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拦截所有请求
 */
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ICache<Object, Object> defaultCache;


    @Autowired
    private FilmService filmService;

    @Autowired
    private SiteApplyService siteApplyService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        fetchCacaheData(request);

        String requestUri = request.getRequestURI();
        if (requestUri.equals("/page/playFilm.html")) {
            Film film = (Film) request.getAttribute("film");

            // 写播放记录cookie
            String cookieKey = "5ifilm.film" + film.getFilmId();
            String cookieValue = film.getFilmId() + "," + URLEncoder.encode(film.getFilmName(), "UTF-8");
            wirteCookie(response, cookieKey, cookieValue);

            // 随机查询10条电影列表放在相关电影栏目中
            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("roundNum", 10);
            List<Film> roundFilmList = filmService.roundQueryFilm(parameter);
            request.setAttribute("roundFilmList", roundFilmList);

            // 更新播放次数
            int currentPlayNum = film.getPlayNum();
            film.setPlayNum(currentPlayNum + 1);
            filmService.updateFilm(film);
        } else if (requestUri.equals("/index.html")) {
            // 今日头版电影（5条）推荐
            List<SlideFilm> slideFilmList = (List<SlideFilm>)defaultCache.get(Constants.CACHE_KEY_SLIDE);
            request.setAttribute("slideFilmList", slideFilmList);

            List<SiteApply> siteApplyList = siteApplyService.queryApplySite(null);
            request.setAttribute("siteApplyList", siteApplyList);
        } else if (requestUri.equals("/filmListByCondition.html") || requestUri.equals("/page/filmListByCondition.html")) {
            // 随机查询10条电影列表放在相关电影栏目中
            Map<String, Object> roundParameter = new HashMap<String, Object>();
            roundParameter.put("roundNum", 20);
            List<Film> roundFilmList = filmService.roundQueryFilm(roundParameter);
            request.setAttribute("roundFilmList", roundFilmList);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private void fetchCacaheData(HttpServletRequest request) {
        /*
         * 取固定缓存数据（系统参数表、电影类型表、地区表）
         *
         * 系统参数、电影类型列表和区域列表，在每个页面几乎都能用到
         */
        Map<String, SystemParam> systemParamMap = (Map<String, SystemParam>)defaultCache.get(Constants.CACHE_KEY_SYSPARAM);
        List<FilmType> filmTypeList = (List<FilmType>) defaultCache.get(Constants.CACHE_KEY_FILMTYPE);
        List<Region> regionList = (List<Region>) defaultCache.get(Constants.CACHE_KEY_REGION);

        // 检查Sex开关，关闭情况则截取掉最后一条伦理片数据
        if (!Constants.switchSex) filmTypeList = filmTypeList.subList(0, filmTypeList.size() - 1);

        request.setAttribute("systemParamMap", systemParamMap);
        request.setAttribute("filmTypeList", filmTypeList);
        request.setAttribute("regionList", regionList);
    }

    private void wirteCookie(HttpServletResponse response, String cookieKey, String cookieValue) {
        Cookie filmHistory = new Cookie(cookieKey, cookieValue);
        filmHistory.setMaxAge(7 * 24 * 60 * 60 * 1000);
        filmHistory.setPath("/");
        response.addCookie(filmHistory);
    }
}
